package org.snail.other.service.impl;

import com.dingtalk.open.client.api.model.corp.Department;
import com.dingtalk.open.client.common.SdkInitException;
import com.dingtalk.open.client.common.ServiceException;
import com.dingtalk.open.client.common.ServiceNotExistException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.log4j.Logger;
import org.snail.common.StringUtils2;
import org.snail.common.dingding.auth.AuthHelper;
import org.snail.common.dingding.department.DepartmentHelper;
import org.snail.common.dingding.exception.OApiException;
import org.snail.common.dingding.utils.JedisUtils;
import org.snail.constant.CacheNameConstant;
import org.snail.constant.ErrCodeConstant;
import org.snail.employee.bean.EmployeesDO;
import org.snail.employee.service.impl.AddressServiceImpl;
import org.snail.exception.BaseException;
import org.snail.exception.CommonException;
import org.snail.exception.EmpException;
import org.snail.other.bean.GroupCondition;
import org.snail.other.bean.GroupDO;
import org.snail.other.bean.GroupNotificationDTO;
import org.snail.other.mapper.GroupMapper;
import org.snail.other.service.GroupService;
import org.snail.other.service.redis.GroupRedis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.xml.bind.JAXBException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

@Service
public class GroupServiceImpl implements GroupService {

    private static final Logger LOGGER =  Logger.getLogger(GroupServiceImpl.class);

    @Autowired
    private GroupMapper groupMapper;
    @Autowired
    private GroupRedis groupRedis;
    @Autowired
    private AddressServiceImpl addressService;
    @Autowired
    private JedisUtils jedisUtils;

    /**
     * 保存群
     * @param group  传入对象GroupDO
     * @throws EmpException
     */
    public void  saveGroup(GroupDO group) throws EmpException {
        if(StringUtils2.objIsNull(group)){
            throw new EmpException(ErrCodeConstant.ILLEGAL_PARAM, "对象不能为空!");
        }
        Long groupId = group.getId();
        if(groupId != null){             //如果不为空，则修改该条数据
            group.setId(groupId);
            group.setUpdateTime(new Date());
            group.setIsDel(0);
            group.setGroupType(group.getGroupType());
            groupMapper.updateGroup(group);
            return;
        }else {
            group.setCreateTime(new Date());
            groupMapper.saveGroup(group);
            //将新增人员添加进去
            List<Integer> empIds = group.getEmpIds();
            if (null == empIds || empIds.size() < 1) {
                return ;
            }
            addressService.insertAddressList(empIds, group.getId());
        }
    }

    /**
     * 查询所有群
     * @param groupCondition
     * @return
     */
    public Map<String,Object> findAllGroupWithPage(GroupCondition groupCondition) throws BaseException {
        Integer startPage = groupCondition.getStartPage();
        Integer pageSize = groupCondition.getPageSize();

        if (startPage != null && pageSize != null) {
            PageHelper.startPage(startPage, pageSize);
        }
        List<GroupDO> groupList = groupMapper.findAllGroup(groupCondition);
        PageInfo pageInfo = new PageInfo(groupList);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageInfo", pageInfo);

        //将group保存一遍redis 以后好查询
        for(GroupDO groupDO : groupList){
            jedisUtils.saveHashCache(CacheNameConstant.GROUP_ID_HASH,groupDO.getId()+"",groupDO);
        }

        return map;
    }

    public List<GroupDO> findAllGroup(GroupCondition groupCondition){
        List<GroupDO> groupList = groupMapper.findAllGroup(groupCondition);
        return groupList;
    }

    /**
     * 删除群
     * @param groupIdList 群id List
     */
    public void deleteGroup(List<Long> groupIdList){

        for(Long groupId :groupIdList ){
            groupMapper.deleteGroup(new GroupCondition(groupId));
        }

    }

    /**
     * 以groupName为条件查询所有员工
     * @param groupCondition
     * @return
     */
        public Map<String, Object> findEmpByGroupName(GroupCondition groupCondition){
        Integer startPage = groupCondition.getStartPage();
        Integer pageSize  = groupCondition.getPageSize();
        if(startPage!=null&&pageSize!=null){
            PageHelper.startPage(startPage,pageSize);
        }
        List<EmployeesDO> employeesDOList = groupMapper.findEmpByGroupId(groupCondition);
        PageInfo pageInfo = new PageInfo(employeesDOList);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageInfo", pageInfo);

        return map;
    }

    /**
     * 获取所有群分类
     * @return
     * @throws JAXBException
     * @throws IOException
     */
    public Map findGroupClassification() throws BaseException {
        Map allHashCache = jedisUtils.getAllHashCache(CacheNameConstant.GROUP_CLASSIFICATION);
        return allHashCache;
    }

    /**
     *获取所有部门
     * @return
     * @throws BaseException
     * @throws OApiException
     * @throws SdkInitException
     * @throws ServiceException
     * @throws ServiceNotExistException
     */
    public List<Department> findAllDepartment() throws BaseException, OApiException, SdkInitException, ServiceNotExistException {
        List<Department> departments = new ArrayList<Department>();
        try{
            departments = DepartmentHelper.listDepartments(AuthHelper.getAccessToken(), "25393462");
        }catch (ServiceException e){
            LOGGER.error("系统繁忙,获取所有部门失败:"+e.getMessage());
        }

        return departments;
    }

    /**
     * 通过分组名删除分组
     * @param classificationName
     */
    public void deleteClassification(String classificationName) throws BaseException {
        if (StringUtils.isEmpty(classificationName)) {
            LOGGER.error("删除群分类缺乏群分类名称！");
            throw new CommonException(ErrCodeConstant.ILLEGAL_PARAM, "删除群分类缺乏群分类名称！");
        }
        jedisUtils.deleteKey(CacheNameConstant.GROUP_CLASSIFICATION, classificationName);
    }

    /**
     * 保存群到指定分组
     */
    public void saveGroupClassification(GroupNotificationDTO groupNotificationDTO) throws FileNotFoundException,  BaseException {
        if (null == groupNotificationDTO || null == groupNotificationDTO.getIds() || groupNotificationDTO.getIds().isEmpty() || StringUtils.isEmpty(groupNotificationDTO.getGroupSortName())) {
            LOGGER.error("群组保存至redis失败！缺失关键参数， groupNotificationDTO: " + groupNotificationDTO);
            throw new CommonException(ErrCodeConstant.ILLEGAL_PARAM, "群组保存至redis失败！缺失关键参数 ");
        }
        if (StringUtils.isEmpty(groupNotificationDTO.getFormerGroupSortName())) {

        }else {
            if (!groupNotificationDTO.getFormerGroupSortName().equals(groupNotificationDTO.getGroupSortName())) {
                groupRedis.deleteClassification(groupNotificationDTO.getFormerGroupSortName());
            }
        }
        List groupsInRedis = new ArrayList();
        for(Long groupId : groupNotificationDTO.getIds()) {
            GroupDO groupById = groupMapper.findGroupById(groupId);
            if (null == groupById) {
                LOGGER.error("根据前端传来的id查询群组详情，失败！群组：" + groupById);
                continue;
            }
            groupsInRedis.add(groupById);
        }
        jedisUtils.saveHashCache(CacheNameConstant.GROUP_CLASSIFICATION, groupNotificationDTO.getGroupSortName(), groupsInRedis);
    }



    /**
     * 根据群id,查找群信息
     */
    public GroupDO findGroupById(Long groupId){
        GroupDO groupById = groupMapper.findGroupById(groupId);
        return groupById;

    }

    public List findAPIGroupInfoByGroupId(Long groupId) {
        return groupMapper.findAPIGroupInfoByGroupId(groupId);
    }

    public List<EmployeesDO> findEmpListByDingId(Long groupId) {
        return groupMapper.findEmpListByDingId(groupId);
    }


    public Set<String> findClassificationNameList() throws CommonException {
        return jedisUtils.getKeysForHash(CacheNameConstant.GROUP_CLASSIFICATION);
    }

    public List<GroupDO> findClassificationDeptList(String sortName) throws BaseException {
        List<GroupDO> hashCache = (List<GroupDO>) jedisUtils.getHashCache(CacheNameConstant.GROUP_CLASSIFICATION, sortName);
        return hashCache;
    }
}